package wens.pig.base.plugin.form;

import com.alibaba.csp.sentinel.util.StringUtil;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.exception.KDBizException;
import kd.bos.form.FormShowParameter;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.field.DateEdit;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.permission.api.PermissionService;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import wens.pig.base.common.consts.breeding.*;
import wens.pig.base.common.consts.stock.*;
import wens.pig.base.utils.DateUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 种猪平台插件 -- 校验当前组织
 * @author xn-lijunjie
 * @since 2022年04月15日-15:27
 */
public class BoarPlatFormPlugin extends AbstractFormPlugin {
    public static final List<String> ORG_PATTERN = Arrays.asList("OF-12", "OF-28", "OF-40", "OF-65", "OF-26", "OF-66");
    private static final String B_ORG_PATTERN = "wens_select_orgpattern";
    /**
     * 业务单据对应业务日期集合
     */
    private static final Map<String, String> BUSINESS_MAP = new HashMap<>();
    static {
        BUSINESS_MAP.put(PigIntroConst.B_PIG_INTRO, PigIntroConst.F_BIZDATE);
        BUSINESS_MAP.put(PigTranConstant.FORMBILLID, PigTranConstant.WENS_DATE);
        BUSINESS_MAP.put(PigReceiveConstant.FORMBILLID, PigReceiveConstant.WENS_RECEIVE_DATE);
        BUSINESS_MAP.put(PigLetTranConstant.FORMBILLID, PigLetTranConstant.WENS_OUTDATE);
        BUSINESS_MAP.put(PigEstrusConst.B_PIG_ESTRUS, PigEstrusConst.F_BIZDATE);
        BUSINESS_MAP.put(PigBreedConstant.FORMBILLID, PigBreedConstant.WENS_BREEDDATE);
        BUSINESS_MAP.put(DeliveryRecordConstant.FORMBILLID, DeliveryRecordConstant.WENS_DELIVERYDATE);
        BUSINESS_MAP.put(WeaningRecordBatConstant.FORMBILLID, WeaningRecordBatConstant.WENS_WEANDATE);
        BUSINESS_MAP.put(AbortionConstant.FORMBILLID, AbortionConstant.WENS_ABORTION_DATE);
        BUSINESS_MAP.put(EmptyRecoveryConst.FORMBILLID, EmptyRecoveryConst.RECOVERY_DATE);
        BUSINESS_MAP.put(PigSelectionConstant.FORMBILLID, PigSelectionConstant.WENS_SELECTDATE);
        BUSINESS_MAP.put(PigletMarketConstant.FORMBILLID, PigletMarketConstant.WENS_MARKETDATE);
        BUSINESS_MAP.put(BreedDeathRecordConstant.FORMBILLID, BreedDeathRecordConstant.WENS_DEATHDATE);
        BUSINESS_MAP.put(PigletDeathRecordConstant.FORMBILLID, PigletDeathRecordConstant.WENS_DEATHDATE);
        BUSINESS_MAP.put(BreedSaleRecordConstant.FORMBILLID, BreedSaleRecordConstant.WENS_SALEDATE);
        BUSINESS_MAP.put(PigletSaleConstant.FORMBILLID, PigletSaleConstant.WENS_SALEDATE);
        BUSINESS_MAP.put(ElimiRecordConstant.FORMBILLID, ElimiRecordConstant.WENS_DATE_ELIMINATION);
        BUSINESS_MAP.put(SemenCheckAddConstant.FORMBILLID, SemenCheckAddConstant.WENS_CHECKDATE);
        BUSINESS_MAP.put(SemenCheckConstant.FORMBILLID, SemenCheckConstant.WENS_CHECKDATE);
        BUSINESS_MAP.put(BreedPigTransferConstant.FORMBILLID, BreedPigTransferConstant.WENS_TRANSFERDATE);
        BUSINESS_MAP.put(PigLetTransferConstant.FORMBILLID, PigLetTransferConstant.WENS_TRANFERDATE);
        BUSINESS_MAP.put(PigsFileConstant.WENS_MEAT_TRANSFER, "wens_file_date");
        BUSINESS_MAP.put("wens_pig_intro_semen", "wens_bizdate");
    }

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        try {
            FormShowParameter formShowParameter = e.getFormShowParameter();
            if (null != formShowParameter) {
                String appId = formShowParameter.getAppId();
                if (StringUtils.isEmpty(appId) || appId.startsWith("wens_cost") || !appId.startsWith("wens_")) {
                    // appId为空 直接通过url访问，这时appId为空 http://127.0.0.1:8080/ierp/index.html?formId=xx&pkId=11111
                    // 不是二开的应用不用校验权限，以兼容从工作流那边进来的,或者是标准产品的上下查
                    // 成本核算的也不需要校验
                    return;
                }
            }

            this.checkOrg(e.getFormShowParameter());
        } catch (KDBizException ex) {
            e.setCancelMessage(ex.getMessage());
            e.setCancel(true);
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        String name = model.getDataEntityType().getName();
        String datename = BUSINESS_MAP.get(name);
        if(StringUtil.isNotBlank(datename)){
            DateEdit dateEdit = this.getControl(datename);
            checkDate(dataEntity,dateEdit);
        }
    }

    private void checkDate(DynamicObject dataEntity, DateEdit dateEdit) {
        MainEntityType dataType = EntityMetadataCache.getDataEntityType(dataEntity.getDynamicObjectType().getName());
        DynamicObject endinitialize = BusinessDataServiceHelper.loadSingle(EndInitializeConstant.FORMBILLID,
                "wens_bizdate,wens_initializestatus",
                new QFilter(EndInitializeConstant.ORG, QCP.equals, dataEntity.getLong(dataType.getMainOrg() + ".id"))
                        .and(EndInitializeConstant.WENS_INITIALIZESTATUS, QCP.equals, "0").toArray());
        if (null != endinitialize) {
            Date wens_bizdate = endinitialize.getDate("wens_bizdate");
            dateEdit.setMinDate(DateUtil.add(wens_bizdate,1));
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        //判断当前组织有没有页面权限
        String permissionItemId = ((FormOperate) args.getSource()).getPermissionItemId();
        String entityId = ((FormOperate) args.getSource()).getEntityId();
        FormShowParameter view = getView().getFormShowParameter();
        PermissionService permissionService = kd.bos.service.ServiceFactory.getService(PermissionService.class);
        if(null != permissionItemId) {
            int hasPer = permissionService.checkPermission(RequestContext.get().getCurrUserId(), RequestContext.get().getOrgId(), "01", view.getAppId(), entityId, permissionItemId);
            if (hasPer == 0) {
                throw new KDBizException("当前组织没有当前单据权限！");
            }
        }
        checkOrg(view);
    }

    private void checkOrg(FormShowParameter view) {
        Object isExtra = view.getCustomParam("isextra");
        DynamicObject orgData = BusinessDataServiceHelper.loadSingle(RequestContext.get().getOrgId(), "bos_org", "orgpattern");

        QFilter filter = new QFilter("wens_orgpattern.fbasedataid.id", QCP.equals, orgData.get("orgpattern.id"));

        if (QueryServiceHelper.exists(B_ORG_PATTERN, filter.toArray())) {
            return;
        }
        DynamicObjectCollection selectedPatterns = QueryServiceHelper.query(B_ORG_PATTERN,
                "wens_orgpattern.fbasedataid.name as patternName,wens_orgpattern.fbasedataid.number as patternNumber"
                , new QFilter[0]);
        DynamicObjectCollection selectedExtraPatterns = QueryServiceHelper.query(B_ORG_PATTERN,
                "wens_mulbasedata.fbasedataid.name as extraName,wens_mulbasedata.fbasedataid.number as extraNumber"
                , new QFilter[0]);

        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(B_ORG_PATTERN, "wens_mulbasedatano_tag", new QFilter[0]);
        String formId = "";
        if(view instanceof ListShowParameter){
            ListShowParameter formShowParameter1 = (ListShowParameter) view;
            formId = formShowParameter1.getBillFormId();
        }else {
            formId = view.getFormId();
        }
        String tag = dynamicObject.getString("wens_mulbasedatano_tag");
        List<String> result = Arrays.asList(tag.split(","));
        String patternNames = "";
        String patternNumbers = "";
        if(result.contains(formId) || null != isExtra){
            patternNames = selectedExtraPatterns.stream().map(p -> p.getString("extraName")).collect(Collectors.joining("、"));
            patternNumbers = selectedExtraPatterns.stream().map(p -> p.getString("extraNumber")).collect(Collectors.joining("、"));
        }


        String patternNo = orgData.getString("orgpattern.number");
        if (selectedPatterns.isEmpty()) {
            if (ORG_PATTERN.contains(patternNo)) {
                return;
            }
            throw new KDBizException("请先配置【选择列表过滤组织形态】单据！");
        }
        if(StringUtils.isEmpty(patternNames)){
            patternNames = selectedPatterns.stream().map(p -> p.getString("patternName")).collect(Collectors.joining("、"));
        }else {
            patternNames = patternNames+"、"+selectedPatterns.stream().map(p -> p.getString("patternName")).collect(Collectors.joining("、"));
        }
        if(StringUtils.isEmpty(patternNumbers)) {
            patternNumbers = selectedPatterns.stream().map(p -> p.getString("patternNumber")).collect(Collectors.joining("、"));
        }else {
            patternNumbers = patternNumbers+"、"+selectedPatterns.stream().map(p -> p.getString("patternNumber")).collect(Collectors.joining("、"));
        }

        if (StringUtils.isNotBlank(patternNumbers)) {
            if (patternNumbers.contains(patternNo)) {
                return;
            }
            throw new KDBizException(String.format("当前所选“业务单元”的『形态』必须为【%s】", patternNames));
        }
        throw new KDBizException("【选择列表过滤组织形态】单据中『组织形态』为空，请检查！");
    }
}
